package com.clip.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.clip.dao.ContactDAO;
import com.clip.dao.ContactGroupDAO;
import com.clip.dao.ContactGroupMappingDAO;
import com.clip.dao.UsermobileinfoDAO;
import com.clip.entity.Contact;
import com.clip.entity.ContactGroup;
import com.clip.entity.ContactGroupMapping;
import com.clip.entity.User;
import com.clip.util.ToolsUtils;

@Service
@Transactional
public class ContactGroupService {
	@Autowired
	private ContactGroupDAO contactGroupDAO;
	@Autowired
	private ContactDAO contactDAO;
	@Autowired
	private ContactGroupMappingDAO contactGroupMappingDAO;
	@Autowired
	private UsermobileinfoDAO usermobileinfoDAO;
	public int createContactGroup(String groupname,User currentUser) {
		List list=this.contactGroupDAO.findByQuery("from ContactGroup cg where cg.groupname='"+groupname+"' and cg.uid="+currentUser.getId());
		if(list!=null&&list.size()>0){
			return 0;
		}else{
			Calendar now=Calendar.getInstance();
			ContactGroup contactGroup=new ContactGroup();
			contactGroup.setUid(currentUser.getId());
			contactGroup.setCreatetime(now.getTimeInMillis());
			contactGroup.setGroupname(groupname);
			contactGroup.setPinyingroupname(ToolsUtils.chinese2pinyin(groupname));
			contactGroup.setMembercount(0);
			this.contactGroupDAO.save(contactGroup);
			return contactGroup.getId();
		}
	}

	public Map<String,Object> loadContactsBesidesGroup(int uid,int groupid) {
		Map<String, Object> rootmap=new LinkedHashMap<String, Object>();
		ContactGroup contactGroup=this.contactGroupDAO.findById(groupid);
		List memberlist=getMembersList(contactGroup.getId());
		String hql = "SELECT c1 FROM Contact c1,Contact c2 WHERE c1.uid="+uid+" AND c1.uid=c2.contactuid AND c2.uid=c1.contactuid AND c1.status=1 AND c2.status=1 order by c1.pinyinname";
		List<Contact> newList=contactDAO.findByQuery(hql);
		for(Contact con : newList){
			if(memberlist.size()>0&&memberlist.contains(con.getContactuid())){
				continue;
			}
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("id", con.getId());
			map.put("name", "<![CDATA["+con.getName()+"]]>");
			map.put("email", con.getContactemail());
			map.put("uid", con.getContactuid());
			String smalllogo=(String) UserService.getUserLogoByUid(con.getContactuid()).get(1);
			map.put("ulogo",ToolsUtils.xmlCDATA(smalllogo));
			rootmap.put("Contact id="+con.getId(), map);
		}
		return rootmap;
	}
	
	public List getMembersList(int groupid){
		List list=new ArrayList();
		List templist=this.contactGroupMappingDAO.findByQuery("from ContactGroupMapping map where map.groupid="+groupid);
		for (Object object : templist) {
			ContactGroupMapping mapping=(ContactGroupMapping) object;
			list.add(mapping.getContactuid());
		}
		return list;
	}

	public Map getExistGroup(int uid,boolean isneedContacts) {
		String hql = "from ContactGroup cg where cg.uid="+uid+" order by cg.pinyingroupname";
		List list=this.contactGroupDAO.findByQuery(hql);
		Map map=new LinkedHashMap();
		for (int i = 0; i < list.size(); i++) {
			ContactGroup contactGroup=(ContactGroup) list.get(i);
			Map temp2=new HashMap();
			temp2.put("groupname", contactGroup.getGroupname());
			temp2.put("pinyingroupname", contactGroup.getPinyingroupname());
			temp2.put("membercount", contactGroup.getMembercount());
			if(isneedContacts){
				List templist=this.contactGroupMappingDAO.findByQuery("from ContactGroupMapping map where map.groupid="+contactGroup.getId());
				for (Object object : templist) {
					Map temp3=new HashMap();
					ContactGroupMapping mapping=(ContactGroupMapping) object;
					
					Contact contact=(Contact) this.contactDAO.findByQuery("from Contact c where c.status=1 and c.uid="+uid+" and c.contactuid="+mapping.getContactuid()).get(0);
					int contactuid=contact.getContactuid();
					temp3.put("hasmobile", isHasBindableMobile(contactuid));
					temp3.put("name", contact.getName());
					temp3.put("email", contact.getContactemail());
					temp3.put("contactuid", contactuid);
					temp2.put("Contact id="+contact.getId(), temp3);
				}
			}
			map.put("ContactGroup id="+contactGroup.getId(), temp2);
		}
		return map;
	}
	
	public boolean isHasBindableMobile(Integer uid){
		String query="from Usermobileinfo info where info.uid='"+uid+"' and info.status=1";
		List list=usermobileinfoDAO.findByQuery(query);
		if(list==null||list.size()<=0){
			return false;
		}else{
			return true;
			
		}
	}

	public Map<String, Object> loadContactsInGroup(int uid,int groupid) {
		Map<String, Object> rootmap=new LinkedHashMap<String, Object>();
		List contactuidslist=loadContactsInsideGroup(uid,groupid);
		for (Object object : contactuidslist) {
			int contactuid=(Integer)object;
			Contact con=getContactByUids(uid,contactuid);
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("id", con.getId());
			map.put("name", "<![CDATA["+con.getName()+"]]>");
			map.put("email", con.getContactemail());
			map.put("uid", con.getContactuid());
			String smalllogo=(String) UserService.getUserLogoByUid(con.getContactuid()).get(1);
			map.put("ulogo",ToolsUtils.xmlCDATA(smalllogo));
			rootmap.put("Contact id="+con.getId(), map);
			
		}
		return rootmap;
	}

	public Contact getContactByUids(int uid1,int uid2){
		List list=this.contactDAO.findByQuery("from Contact c where c.status=1 and c.uid="+uid1+" and c.contactuid="+uid2);
		if(list!=null&&list.size()==1){
			Contact contact=(Contact) list.get(0);
			return contact;
		}else
			return null;
	}
	
	/**
	 * @param uid
	 * @param groupid
	 * @return List<uid>
	 */
	public List loadContactsInsideGroup(int uid,int groupid){
		ContactGroup contactGroup=this.contactGroupDAO.findById(groupid);
		List memberlist=this.contactGroupMappingDAO.findByQuery("from ContactGroupMapping map where map.groupid="+groupid);
		if(contactGroup.getMembercount()!=memberlist.size()){
			contactGroup.setMembercount(memberlist.size());
			this.contactGroupDAO.attachDirty(contactGroup);
		}
		List list=new ArrayList();
		for (Object object : memberlist) {
			ContactGroupMapping mapping=(ContactGroupMapping) object;
			
			Contact con=(Contact) this.contactDAO.findByQuery("from Contact c where c.status=1 and c.uid="+uid+" and c.contactuid="+mapping.getContactuid()).get(0);
			list.add(mapping.getContactuid());
			
		}
		return list;
	}

	public ContactGroup addContacts2Group(int groupid, String contacts) {
		int addcount=0;
		if(contacts.indexOf(",")>0){
			String [] ss=contacts.split(",");
			for (String string : ss) {
				saveContactGroupMap(string,groupid);
				addcount++;
			}
		}else{
			saveContactGroupMap(contacts,groupid);
			addcount++;
		}
		ContactGroup contactGroup=this.contactGroupDAO.findById(groupid);
		contactGroup.setMembercount(contactGroup.getMembercount()+addcount);
		this.contactGroupDAO.attachDirty(contactGroup);
		return contactGroup;
		
	}
	
	private void saveContactGroupMap(String contactuidstr,int groupid){
		int contactuid=Integer.parseInt(contactuidstr);
		ContactGroupMapping mapping=new ContactGroupMapping();
		mapping.setContactuid(contactuid);
		mapping.setGroupid(groupid);
		this.contactGroupMappingDAO.save(mapping);
	}

	public ContactGroup removeContactsFromGroup(int groupid, String contacts) {
		int removecount=0;
		if(contacts.indexOf(",")>0){
			String [] ss=contacts.split(",");
			for (String string : ss) {
				removecount++;
			}
		}else{
			removecount++;
		}
		ContactGroup contactGroup=this.contactGroupDAO.findById(groupid);
		int count=contactGroup.getMembercount()-removecount;
		if(count<0)
			count=0;
		contactGroup.setMembercount(count);
		this.contactGroupDAO.attachDirty(contactGroup);
		String query="delete from ContactGroupMapping map where map.groupid="+groupid+" and map.contactuid in ("+contacts+")";
		this.contactGroupMappingDAO.updateByQuery(query);
		return contactGroup;
	}

	public boolean updateGroupName(int groupid, String groupname) {
		List list=this.contactGroupDAO.findByQuery("from ContactGroup cg where cg.id<>"+groupid+" and cg.groupname='"+groupname+"'");
		if(list!=null&&list.size()>0){
			return false;
		}else{
			ContactGroup contactGroup=this.contactGroupDAO.findById(groupid);
			if(!contactGroup.getGroupname().equals(groupname)){
				contactGroup.setGroupname(groupname);
				contactGroup.setPinyingroupname(ToolsUtils.chinese2pinyin(groupname));
				this.contactGroupDAO.attachDirty(contactGroup);
			}
			return true;
		}
	}

	public boolean deleteContactGroup(int uid, int groupid) {
		ContactGroup contactGroup=this.contactGroupDAO.findById(groupid);
		if(contactGroup==null||contactGroup.getUid()!=uid){
			return false;
		}else{
			this.contactGroupDAO.delete(contactGroup);
			return true;
		}
	}

	public Map<String, Object> loadSubscribesBesidesGroup(int uid, int groupid) {
		Map<String, Object> rootmap=new LinkedHashMap<String, Object>();
		ContactGroup contactGroup=this.contactGroupDAO.findById(groupid);
		List memberlist=getMembersList(contactGroup.getId());
		String hql = "FROM Contact c WHERE c.uid="+uid+" AND c.status=1 and c.contacttypeid=2 order by c.pinyinname";
		List<Contact> newList=contactDAO.findByQuery(hql);
		for(Contact con : newList){
			if(memberlist.size()>0&&memberlist.contains(con.getContactuid())){
				continue;
			}
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("id", con.getId());
			map.put("name", "<![CDATA["+con.getName()+"]]>");
			map.put("email", con.getContactemail());
			map.put("uid", con.getContactuid());
			String smalllogo=(String) UserService.getUserLogoByUid(con.getContactuid()).get(1);
			map.put("ulogo",ToolsUtils.xmlCDATA(smalllogo));
			rootmap.put("Contact id="+con.getId(), map);
		}
		return rootmap;
	}

	public List getUserGroups(int uid) {
		String hql = "from ContactGroup cg where cg.uid="+uid+" order by cg.pinyingroupname";
		List list=this.contactGroupDAO.findByQuery(hql);
		return list;
	}

	public List getExistCircles(int uid) {
		String hql = "from ContactGroup cg where cg.uid="+uid+" order by cg.pinyingroupname";
		List list=this.contactGroupDAO.findByQuery(hql);
		return list;
	}

	public boolean checkIsBelongToUser(int uid, int circleid) {
		String hql = "select cg.groupname from ContactGroup cg where cg.uid="+uid+" and cg.id="+circleid;
		List list=this.contactGroupDAO.findByQuery(hql);
		if(list!=null&&list.size()>0){
			return true;
		}else
			return false;
	}
	
}
